#pragma once

#include<iostream>
using namespace std;
#include<vector>

namespace my
{
    template<class T>
    class myless
    {
    public:
        bool operator()(const T& x, const T& y)
        {
            return x < y;
        }
    };

    template<class T>
    class mygreater
    {
    public:
        bool operator()(const T& x, const T& y)
        {
            return x > y;
        }
    };

	template<class T, class Container = vector<T>, class Compare = myless<T>>
	class priority_queue
	{
	public:
		priority_queue(const Compare& comp = Compare(), const Container& cntr = Container())
			:_con(cntr)
			,_comp(comp)
		{}

		template <class InputIterator>
		priority_queue(InputIterator first, InputIterator last,
			const Compare& comp = Compare(), const Container& cntr = Container())
			: _comp(comp)
			, _con(cntr)
		{
			while (first != last)
			{
				_con.push_back(*first);
				first++;
			}

            for (int i = (_con.size() - 2) / 2; i >= 0; i--)
            {
                AdjustDown(i);
            }
		}

        bool empty() const
        {
            return _con.empty();
        }

        size_t size() const
        {
            return _con.size();
        }

        const T& top() const
        {
            return _con[0];
        }

        void push(const T& val)
        {
            _con.push_back(val);
            AdjustUp(_con.size() - 1);
        }

        void pop()
        {
            swap(_con[0], _con[_con.size() - 1]);
            _con.pop_back();
            AdjustDown(0);
        }

        void AdjustUp(int child)
        {
            int parent = (child - 1) / 2;
            while (child > 0)
            {
                if (_comp(_con[child], _con[parent]))
                    swap(_con[parent], _con[child]);
                else
                    break;
                child = parent;
                parent = (child - 1) / 2;
            }
        }

        void AdjustDown(int parent)
        {
            int child = parent * 2 + 1;
            while (child < _con.size())
            {
                if ((child + 1 < _con.size()) && _comp(_con[child + 1], _con[child]))
                    child++;
                if (_comp(_con[child], _con[parent]))
                    swap(_con[parent], _con[child]);
                else
                    break;
                parent = child;
                child = 2 * parent + 1;
            }
        }

	private:
		Container _con;
		Compare _comp;
	};

    void Test_priority_queue()
    {
        int a[10] = { 3, 6, 4, 5, 9, 8, 1, 0, 7, 2 };
        priority_queue<int> pq(a, a + 10);
        cout << pq.top() << endl;
        pq.push(-3);
        cout << pq.top() << endl;
        pq.pop();
        cout << pq.top() << endl;
        while (!pq.empty())
        {
            cout << pq.top() << ' ';
            pq.pop();
        }
    }
}